package states

import (
	"go_server/game_server/api/service/build_resource"
	"go_server/game_server/dao"
	"go_server/game_server/dao/count_down_dao"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"go_server/zinx/znet"
	"time"
)

type GetStateListApi struct {
	znet.BaseRouter
}

// 获取玩家交互相关状态信息
func (*GetStateListApi) Handle(request ziface.IRequest) {
	msg := &pb.GetStateListC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	row := count_down_dao.GetCountDownByRoleId(roleId, []string{"event_list", "guide_list"})
	row1 := dao.GetBuildRobotInfo(roleId)

	eventList := make([]int32, 0)
	guideList := make([]int32, 0)
	buildResourceData := make(map[int32]map[int32][]int64)
	buildStates := make(map[int32]int64)
	curTime := time.Now().UnixMilli()

	if row != nil {
		if row.EventList != nil {
			eventList = row.EventList
		}

		if row.GuideList != nil {
			guideList = row.GuideList
		}

		if row.BuildStates.Data() != nil {
			buildStates = row.BuildStates.Data()
		}
	}

	if row1 != nil && row1.BuildResourceData.Data() != nil {
		buildResourceData = row1.BuildResourceData.Data()
	}

	if len(buildResourceData) > 0 {
		for buildId, buildInfo := range buildResourceData {
			totalTime := int64(0) // 累计采集时间

			for _, robotInfo := range buildInfo {
				if robotInfo[0] == build_resource.START_COLLECT_RESOURCE {
					totalTime += curTime - robotInfo[1]
				}

				// 历史之前累计采集时间，未被采集
				if robotInfo[2] > 0 {
					totalTime += robotInfo[2]
				}
			}
			buildStates[buildId] = totalTime
		}
	}

	res := &pb.GetStateListS2C{
		EventList:   eventList,
		GuideList:   guideList,
		BuildStates: buildStates,
	}

	zlog.Infof("res=%v", res)

	// 优先返回下行
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetStateList), res)
}
